const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const log = require('j7/log');
const BaseTask = require('./basetask');
const factory = require('./factory');
const serviceFactory = require('../services/factory');
const metaFactory = require('../metadata/factory');

class DbSpider extends BaseTask {

  async init() {
    const netList = metaFactory.getNetList();
    netList.forEach
    (
      (net) => {
       this.initNet(net);
     });
  }

  async initNet(net) {
    const events = [];
    net['Events'].forEach
    (
      (eventConf) => {
        const event = {
            'eventConf': eventConf,
            'progressInfo': {
              'pullCount': 0,
              'eventCount': 0,
              'pullLastIdx': 0,
              'pullMaxIdx': 0,

              'procPullCount': 0,
              'procEventCount': 0,
              'procLastIdx': 0,
              'procmaxIdx': 0
            }
        };
        events.push(event);
        this.createPullDbEventService(net, event);
        this.createDbEventProcessService(net, event);
      });
    await utils.sleep(1000 * 10);
    this.outputProgressInfo(net, events);
  }

  createPullDbEventService(net, event) {
    const pullDbEventService = serviceFactory.create('PullDbEvent');
    event['pullDbEventService'] = pullDbEventService;
    pullDbEventService.init(net, event);
    return pullDbEventService;
  }

  createDbEventProcessService(net, event) {
    const dbEventProcessService = serviceFactory.create('DbEventProcess');
    event['dbEventProcessService'] = dbEventProcessService;
    dbEventProcessService.init(net, event);
    return dbEventProcessService;
  }

  async outputProgressInfo(net, events) {
    let count = 0;
    while (true) {
      log.info('----------------------------------------------------------');
      events.forEach
      (
        (event) => {
          const eventConf = event['eventConf'];
          const progInfo = event['progressInfo'];
          const pullService = event['pullDbEventService'];
          const procService = event['dbEventProcessService'];
          const logObj = 'net_id: ' + net['net_id'] + ' ' +
                eventConf['contract_name'] + '.' +
                eventConf['event_name'] + ' ' +
                ' A_pullCount:' + progInfo['pullCount'] +
                ' A_eventCount:' + progInfo['eventCount'] +
                ' A_lastIdx:' + progInfo['pullLastIdx'] +
                ' A_maxIdx:' + pullService.getMaxIdx().toString() +

                ' B_pullCount:' + progInfo['procPullCount'] +
                ' B_eventCount:' + progInfo['procEventCount'] +
                ' B_lastIdx:' + progInfo['procLastIdx'] +
                ' B_maxIdx:' + procService.getMaxIdx().toString() +
                '';
          log.info(logObj);
        }
      );
      await utils.sleep(1000 * 10);
    }
  }

}

module.exports = DbSpider;
